# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
  
  def error_messages_for(*params)
    options = params.last.is_a?(Hash) ? params.pop.symbolize_keys : {}
    if object = options.delete(:object)
      objects = [object].flatten
    else
      objects = params.collect {|object_name| instance_variable_get("@#{object_name}") }.compact
    end
    error_messages = objects.map do |object| 
      sort_show_error_msg(object)
    end
    count = objects.inject(0) {|sum, object| sum + error_messages[objects.index(object)].size}
    unless count.zero?
      html = {}
      [:id, :class].each do |key|
        if options.include?(key)
          value = options[key]
          html[key] = value unless value.blank?
        else
          html[key] = 'errorExplanation'
        end
      end
      error_message = "个问题"
      header_message = "存在#{count}#{error_message}"
      # Change 'error' to 'errors' for english setups void of a localization plugin
      header_message.gsub!("error", "errors") if header_message.include?(error_message) and count > 1
      content_tag(:div,
        content_tag(options[:header_tag] || :h2, header_message) <<
        content_tag(:p, ('下列项目中存在问题：')) <<
        content_tag(:ul, error_messages),
        html
      )
    else
        ''
    end
  end
  
  def sort_show_error_msg(obj)
    full_messages= []
    translated_label = obj.class::HUMANIZED_ATTRIBUTES rescue {}
    msg_arr = sort_error(obj)
    msg_arr.each do |attr, msg|
      next if msg.nil?
      if attr == "base"
        full_messages << (msg)
      else
        msg += '。' unless msg =~ /。|。$/
        label ||= obj.class.human_attribute_name(attr)
        full_messages << content_tag(:li, content_tag(:span, "#{label + " " + (msg)}"))
      end
    end
    return full_messages
  end

  def sort_error(obj)
    msg_arr = obj.errors.sort 
    hidden_attr = obj.class::HIDDEN_ATTRIBUTES rescue []
    msg_arr.delete_if{ |key, val| hidden_attr.include?(key) } unless hidden_attr.blank?
    # 排序
    hash_field_orders = obj.class::HUMANIZED_ATTRIBUTES_ORDERS rescue {}
    # 未设置排序的字段排在最后
    max = hash_field_orders.values.sort.last.to_i + 1
    unless hash_field_orders.blank? 
      msg_arr = msg_arr.sort do |key_a, key_b|
        value_a = hash_field_orders[key_a[0].to_sym].blank? ? max : hash_field_orders[key_a[0].to_sym]
        value_b = hash_field_orders[key_b[0].to_sym].blank? ? max : hash_field_orders[key_b[0].to_sym]
        value_a <=> value_b
      end
    end
    msg_arr
  end
end
